//
//  RoomSelectNextViewController.m
//  QRMaster
//
//  Created by myApple on 15/6/23.
//  Copyright (c) 2015年 myApple. All rights reserved.
//

#import "RoomSelectNextViewController.h"
#import "AllocateRoomModel.h"
#import "RequestNetWork.h"
#import "PromptInfoView.h"
#import "AllocateRoomModel.h"
#import "validateInputValue.h"
#import "StaffTimeChooseView.h"
#import "AssignStaffRoomTimeCell.h"
#import "AllocateRoomProcess.h"

@interface RoomSelectNextViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    UITableView * roomTableView;
    NSMutableArray * selectRoomIdArray;
    UIImageView * submitImageView;
    UILabel * submitLabel;
    UIButton * backBtn;
    UILabel * bottomLabel;
    UIImageView * bottomLeftImgView;
    UIView * buttonDeleteView;
    AllocateRoomProcess * dataProcess;
}

@end

@implementation RoomSelectNextViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        dataProcess = [[AllocateRoomProcess alloc]init];
        selectRoomIdArray = [[NSMutableArray alloc]init];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = NSLocalizedString(@"roomChoose", nil);
    [self prepareTableView];
    [self prepareNavBtn];
    // Do any additional setup after loading the view.
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    submitImageView.hidden = NO;
    backBtn.hidden = NO;
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillAppear:animated];
    submitImageView.hidden = YES;
    backBtn.hidden = YES;
}


-(void)setAllocatedRoomArray:(NSMutableArray *)allocatedRoomArray
{
    _allocatedRoomArray = allocatedRoomArray;
    selectRoomIdArray = [allocatedRoomArray mutableCopy];
}

-(void)prepareNavBtn
{
    submitImageView = [[UIImageView alloc]initWithFrame:CGRectMake(UI_SCREEN_WIDTH - 66, 2, 50, 40)];
    submitImageView.userInteractionEnabled = NO;
    UITapGestureRecognizer * submitTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(makeSureChoose)];
    [submitImageView addGestureRecognizer:submitTap];
    [self.navigationController.navigationBar addSubview:submitImageView];
    
    submitLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 10, 50, 20)];
    submitLabel.text = NSLocalizedString(@"authenSubmit",@"完成");
    submitLabel.textColor = UIColorFromRGBAndA(0x7dc234, 0.5);
    submitLabel.font = [UIFont systemFontOfSize:15.0];
    submitLabel.textAlignment = NSTextAlignmentRight;
    [submitImageView addSubview:submitLabel];
    
    float x = 0;
    float y = 0;
    float width = 56;
    float height = 40;
    backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(x, y, width, height);
    [backBtn addTarget:self action:@selector(userBack) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationController.navigationBar addSubview:backBtn];
}

-(void)prepareTableView
{
    float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
    float ScreenHeight = UI_SCREEN_HEIGHT;
    float x = 0;
    float y = 0;
    float width = ScreenWidth;
    float height = ScreenHeight - 64;
    
    roomTableView = [[UITableView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    roomTableView.dataSource = self;
    roomTableView.delegate = self;
    roomTableView.tableFooterView = [[UIView alloc]init];
    roomTableView.tableFooterView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:roomTableView];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _roomArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 56;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    AssignRoomTimeModel * model = _roomArray[indexPath.row];
    AssignStaffRoomTimeCell * cell = [AssignStaffRoomTimeCell cellWithTableView:tableView];
    cell.accessoryType = UITableViewCellAccessoryNone;
    for (NSString * roomId in selectRoomIdArray) {
        if ([roomId isEqualToString:model.roomId]) {
             cell.accessoryType = UITableViewCellAccessoryCheckmark;
        }
    }
    [cell setData:model];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    AssignRoomTimeModel * model = _roomArray[indexPath.row];
    UITableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
    if (cell.accessoryType == UITableViewCellAccessoryCheckmark ) {
        cell.accessoryType = UITableViewCellAccessoryNone;
        [selectRoomIdArray removeObject:model.roomId];
    }
    else
    {
        [selectRoomIdArray addObject:model.roomId];
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
    [self judgeSelect];
}

#pragma mark -----------确定选择
-(void)makeSureChoose
{
    NSString *paramStr=@"";
    NSUserDefaults * userInfo = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    NSMutableString * roomString = [[NSMutableString alloc]init];
    for (NSString * roomId in selectRoomIdArray) {
        [roomString appendString:roomId];
        [roomString appendString:@","];
    }
    if(roomString.length > 0)
    {
        NSRange range;
        range.location = roomString.length - 1;
        range.length = 1;
        [roomString deleteCharactersInRange:range];
    }
    [postDict setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
    [postDict setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
    [postDict setValue:[QRSingleton sharedQRSingleton].communityId forKey:@"communityId"];
    if ([_guestOrStaff isEqualToString:@"1"]) {
        [postDict setValue:_memeberID forKey:@"userId"];
        [postDict setValue:roomString forKey:@"roomStr"];
        paramStr = POST(ADDSTAFFROOM);
    }
    else if([_guestOrStaff isEqualToString:@"0"])
    {
        [postDict setValue:_memeberID forKey:@"userId"];
        [postDict setValue:roomString forKey:@"roomStr"];
         paramStr = POST(ADDCLIENTROOMPOWER);
    }
    else
    {
        [postDict setValue:_groupId forKey:@"groupId"];
        [postDict setValue:_email forKey:@"email"];
        [postDict setValue:_mobile forKey:@"mobile"];
        if (_mobile != nil && ![_mobile isEqualToString:@""] && [validateInputValue isPureNumandCharacters:_mobile]) {
            [postDict setValue:_areaCode forKey:@"areaCode"];
        }
        [postDict setValue:roomString forKey:@"groupRoom"];
        
        paramStr = POST(EDITGROUPCLIENTROOM);
    }
    __block RoomSelectNextViewController * weakSelf = self;
    RequestNetWork * rnw = [[RequestNetWork alloc]init];
    [self startWaiting:nil color:nil addToView:self.view];
    [rnw initWithPath:paramStr params:postDict block:^(id downLoadData, id error)
     {
         [self stopWaiting];
         NSArray * data = [downLoadData objectForKey:@"data"];
         if (data) {
             [PromptInfoView showMessage:NSLocalizedString(@"modifySuccess", nil) superView:weakSelf.view];
             [self.navigationController popViewControllerAnimated:YES];
         }
         else
         {
            [PromptInfoView showMessage:[error objectForKey:@"info"]];
         }
         
     }
     ];
}

#pragma mark ----------用户自定义返回键
-(void)userBack
{
    if ([self judgeSelect]) {
        UIAlertView * alterView = [[UIAlertView alloc]initWithTitle:nil message:NSLocalizedString(@"shouldSave", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"notSave", nil) otherButtonTitles:NSLocalizedString(@"save", nil), nil];
        [alterView show];
    }
    else
    {
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        [self makeSureChoose];
    }
    else
    {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

-(BOOL)judgeSelect
{
    if (![dataProcess arrayItemIsSame:selectRoomIdArray withArray:_allocatedRoomArray]) {
        submitImageView.userInteractionEnabled = YES;
        submitLabel.textColor = UIColorFromRGB(0x7dc234);
        return YES;
    }
    else
    {
        submitImageView.userInteractionEnabled = NO;
        submitLabel.textColor = UIColorFromRGBAndA(0x7dc234, 0.5);
        return NO;
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
